<%@ page contentType="text/html;charset=UTF-8" language="java" %>
<!DOCTYPE html>
<html xmlns:th="http://www.w3.org/1999/xhtml">
<head>
    <title>校园信息网聊天系统</title>
    <script type="text/javascript" src="http://ajax.microsoft.com/ajax/jquery/jquery-1.4.min.js"></script>
    <script src="http://cdn.bootcss.com/stomp.js/2.3.3/stomp.min.js"></script>

    <script src="https://cdnjs.cloudflare.com/ajax/libs/sockjs-client/1.1.4/sockjs.min.js"></script>
    <script  type="text/javascript" src="${pageContext.request.contextPath}/js/websocket/ajaxfileupload.js"></script>
</head>

<body>
<div style="margin: auto;text-align: center">
    <h1>校园信息网及时通讯系统</h1>
</div>
<br/>
<div style="margin: auto;text-align: center">
    <select id="onLineUser">
        <option>--所有--</option>
    </select>
    <input id="text" type="text" />
    <button onclick="send()">发送消息</button>

    <input type='file' name='files' id="fileUpload" onchange="uploadExcelFile();"/>

    <button id="start" class="ui-btn ui-btn-primary" disabled>录音</button>
    <button id="stop" class="ui-btn ui-btn-primary" disabled>停止</button>
    <div id="audio-container"></div>
    <script src="${pageContext.request.contextPath}/js/websocket/recorder.js"></script>
    <script>
        window.onload = function(){
            var start = document.querySelector('#start');
            var stop = document.querySelector('#stop');
            var container = document.querySelector('#audio-container');
            var recorder = new Recorder({
                sampleRate: 44100, //采样频率，默认为44100Hz(标准MP3采样率)
                bitRate: 128, //比特率，默认为128kbps(标准MP3质量)
                success: function(){ //成功回调函数
                    start.disabled = false;
                },
                error: function(msg){ //失败回调函数
                    alert(msg);
                },
                fix: function(msg){ //不支持H5录音回调函数
                    alert(msg);
                }
            });


            start.addEventListener('click',function(){
                this.disabled = true;
                stop.disabled = false;
                var audio = document.querySelectorAll('audio');
                for(var i = 0; i < audio.length; i++){
                    if(!audio[i].paused){
                        audio[i].pause();
                    }
                }
                recorder.start();
            });
            stop.addEventListener('click',function(){
                this.disabled = true;
                start.disabled = false;
                recorder.stop();
                recorder.getBlob(function(blob){
                    blobToDataURL(blob, function (dataurl) {
                        var selectText = $("#onLineUser").find("option:selected").text();
                        if(selectText=="--所有--"){
                            selectText = "All";
                        }else{
                            var imgurl=document.getElementById('username').value+"对"+selectText+"说：<audio src=\""+dataurl+"\" controls=\"controls\">\n" +
                                "</audio><br/>"
                            document.getElementById("message").innerHTML=imgurl;
                        }
                        var username=document.getElementById('username').value;
                        $.ajax({
                            type: "post",
                            url: "./questionType/importAudio",
                            data:{"dataurl":dataurl,"username":username,"selectText":selectText},
                            success: function(r) {
                            }
                        });
                    });
                });
            });
        };

        function blobToDataURL(blob, callback) {
            var a = new FileReader();
            a.onload = function (e) { callback(e.target.result); }
            a.readAsDataURL(blob);
        }

        function uploadAudioFile(files) {
            var formData = new FormData();
            formData.append('files',files);

            $.ajax({
                type:'POST',
                url: "/questionType/importAudio",
                data:formData,
                contentType:undefined,
                mimeType:"multipart/form-data",
                success:function(data){
                }
            });
        }

    </script>
</div>
<br>
<div style="margin-right: 10px;text-align: right">
    <button onclick="closeWebSocket()">关闭连接</button>
</div>
<hr/>
<div id="message" style="text-align: center;"></div>
<input  type="text" th:value="${username}" id="username" style="display: none" />


<script>
    function uploadExcelFile() {
        var selectText = $("#onLineUser").find("option:selected").text();
        if(selectText=="--所有--"){
            selectText = "All";
        }
        var username=document.getElementById('username').value;
        $.ajaxFileUpload({
            url:"./questionType/importExcel",
            type:"POST",
            fileElementId :"fileUpload",
            data:{"username":username,"selectText":selectText},
            success:function (data) {
                var selectText = $("#onLineUser").find("option:selected").text();
                if(selectText!="--所有--"){
                    var imgurl=document.getElementById('username').value+"对"+selectText+"说：<img src=\""+data.activeElement.innerHTML+"\" width=\"100\" /><br/>";
                    document.getElementById("message").innerHTML=imgurl;
                }
                $("#fileUpload").replaceWith('<input type=\'file\' name=\'files\' id="fileUpload" onchange="uploadExcelFile()"/>');
                    $("#targetFile").on("change", function(){
                        uploadExcelFile();
                });
            },
            error:function(erro){
                console.log("图片上传失败！");
            }
        });
    }
</script>
</body>


<script type="text/javascript">
    var webSocket;
    var commWebSocket;
    if ("WebSocket" in window)
    {

        webSocket = new WebSocket("ws://localhost:9030/websocket/"+document.getElementById('username').value);

        //连通之后的回调事件
        webSocket.onopen = function()
        {
            //webSocket.send( document.getElementById('username').value+"已经上线了");
            console.log("已经连通了websocket");
            var myDate = new Date();
            console.log("连通时间："+myDate);
            setMessageInnerHTML("已经连通了websocket");
        };

        //接收后台服务端的消息
        webSocket.onmessage = function (evt)
        {
            debugger;
            var received_msg = evt.data;
            console.log("数据已接收:" +received_msg);
            var obj = JSON.parse(received_msg);
            console.log("可以解析成json:"+obj.messageType);
            //1代表上线 2代表下线 3代表在线名单 4代表普通消息
            if(obj.messageType==1){
                //把名称放入到selection当中供选择
                var onlineName = obj.username;
                var option = "<option>"+onlineName+"</option>";
                $("#onLineUser").append(option);
                setMessageInnerHTML(onlineName+"上线了");
            }
            else if(obj.messageType==2){
                $("#onLineUser").empty();
                var onlineName = obj.onlineUsers;
                var offlineName = obj.username;
                var option = "<option>"+"--所有--"+"</option>";
                for(var i=0;i<onlineName.length;i++){
                    if(!(onlineName[i]==document.getElementById('username').value)){
                        option+="<option>"+onlineName[i]+"</option>"
                    }
                }
                $("#onLineUser").append(option);

                setMessageInnerHTML(offlineName+"下线了");
            }
            else if(obj.messageType==3){
                var onlineName = obj.onlineUsers;
                var option = null;
                for(var i=0;i<onlineName.length;i++){
                    if(!(onlineName[i]==document.getElementById('username').value)){
                        option+="<option>"+onlineName[i]+"</option>"
                    }
                }
                $("#onLineUser").append(option);
                console.log("获取了在线的名单"+onlineName.toString());
            }
            else if(obj.messageType==4){
                setMessageInnerHTML(obj.fromusername+"对"+obj.tousername+"说："+obj.textMessage);
            }
            else if(obj.messageType==5){
                setImgMessageInnerHTML(obj.fromusername,obj.tousername,obj.textMessage)
            }
            else if(obj.messageType==6){
                setAudioMessageInnerHTML(obj.fromusername,obj.tousername,obj.textMessage)
            }

        };

        //连接关闭的回调事件
        webSocket.onclose = function()
        {
            var myDate = new Date();
            console.log("关闭时间："+myDate);
            console.log("连接已关闭...");
            setMessageInnerHTML("连接已经关闭....");
        };
    }
    else{
        // 浏览器不支持 WebSocket
        alert("您的浏览器不支持 WebSocket!");
    }
    //将消息显示在网页上
    function setMessageInnerHTML(innerHTML) {
        debugger;
        document.getElementById('message').innerHTML += innerHTML + '<br/>';
    }
    //将图片消息显示在网页上
    function setImgMessageInnerHTML(fromusername,tousername,textMessage) {
        debugger;
        var imgurl=fromusername+"对"+tousername+"说：<img src=\"http://localhost:9090"+textMessage+"\" height=\"100\" width=\"100\" /><br/>"
        console.log(imgurl);
        document.getElementById("message").innerHTML=imgurl;
    }
    //将语音消息显示在网页上
    function setAudioMessageInnerHTML(fromusername,tousername,textMessage) {
        debugger;
        var imgurl=fromusername+"对"+tousername+"说：<audio src=\"http://localhost:9090"+textMessage+"\" controls=\"controls\">\n" +
            "</audio><br/>"
        console.log(imgurl);
        document.getElementById("message").innerHTML=imgurl;
    }

    function closeWebSocket() {
        debugger;
        //直接关闭websocket的连接
        webSocket.close();
    }

    function send() {
        debugger;
        var selectText = $("#onLineUser").find("option:selected").text();
        if(selectText=="--所有--"){
            selectText = "All";
        }
        else{
            setMessageInnerHTML(document.getElementById('username').value+"对"+selectText+"说："+ $("#text").val());
        }
        var message = {
            "message":document.getElementById('text').value,
            "username":document.getElementById('username').value,
            "to":selectText
        };
        webSocket.send(JSON.stringify(message));
        $("#text").val("");

    }

</script>


</html>